<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/29/24
 * Time: 5:08 PM
 */

namespace App\Console\Commands;

use App\Models\WechatAccount;
use App\Models\WechatCorp;
use App\Services\KfAccountService;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use App\Models\WechatAccountCustomer as AcModel;
use Illuminate\Support\Facades\Log;


/**
 * 成员客户统计
 *
 * Class Push
 * @package App\Console\Commands
 */
class WechatAccountCustomer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:account_customer';


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '成员客户统计';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     *
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        Log::info('同步成员客户信息');
        $corpIds = WechatCorp::query()->pluck('corp_id')->toArray();

        $client  = new Client();
        $service = new KfAccountService();
        foreach ($corpIds as $corpId) {
            $userIds = WechatAccount::query()->where('corp_id', $corpId)->pluck('user_id')->toArray();
            if (!$userIds) {
                continue;
            }
            $token = $service->getReplaceAccessToken($corpId);
            foreach ($userIds as $userId) {
                // 获取成员外部客户总数量
                $response = $client->request('GET', sprintf($service->api['externalcontact_list'], $token, $userId));
                if ($response->getStatusCode() != 200) {
                    continue;
                }
                $content = $response->getBody()->getContents();
                $data    = json_decode($content, true);
                if ($data['errcode'] != 0) {
                    continue;
                }
                if (!$externalUserids = $data['external_userid'] ?? []) {
                    continue;
                }
                foreach ($externalUserids as $externalUserid) {
                    $res = $client->request('GET', sprintf($service->api['externalcontact_detail'], $token, $externalUserid));
                    if ($res->getStatusCode() != 200) {
                        continue;
                    }
                    $con = $res->getBody()->getContents();
                    $arr = json_decode($con, true);
                    if (($arr['errcode'] ?? -1) != 0) {
                        continue;
                    }
                    $externalContact = $arr['external_contact'] ?? [];
                    $followUser      = $arr['follow_user'][0] ?? [];

                    $ac                = AcModel::query()->firstOrNew([
                        'corp_id' => $corpId, 'account_id' => $userId, 'customer_id' => $externalUserid
                    ]);
                    $ac->customer_name = $externalContact['name'] ?? '';
                    $ac->customer_type = $externalContact['type'] ?? 1;
                    $ac->avatar        = $externalContact['avatar'] ?? '';
                    $ac->gender        = $externalContact['gender'] ?? 0;
                    $ac->add_time      = date('Y-m-d', $followUser['createtime'] ?? null);
                    $ac->add_way       = $followUser['add_way'] ?? 0;
                    $ac->save();
                }
            }
        }

    }


}
